package com.ruoyi.web.controller.createcommand;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.basedata.domain.TerminalsDb;
import com.ruoyi.basedata.service.ITerminalsDbService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.datastatistics.domain.createcommand.PresetCommandDataInfo;
import com.ruoyi.datastatistics.service.TerminalsDbCommandService;
import org.apache.commons.codec.DecoderException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author TsingYu
 * @version 1.0
 * @date 2025/1/10 11:04
 */
@RestController
@RequestMapping("/terminalsDbCommand")
public class TerminalsDbCommandController extends BaseController {

    private final ITerminalsDbService terminalsDbService;
    private final TerminalsDbCommandService terminalsDbCommandService;

    public TerminalsDbCommandController(ITerminalsDbService terminalsDbService, TerminalsDbCommandService terminalsDbCommandService) {
        this.terminalsDbService = terminalsDbService;
        this.terminalsDbCommandService = terminalsDbCommandService;
    }

    /**
     * 下发命令——多参数读取
     */
    @PostMapping("/sendPresetReadCommand")
    @PreAuthorize("@ss.hasPermi('terminalsDbCommand:read')")
    public AjaxResult sendPresetReadCommand(@RequestBody JSONObject jsonObject) {
        List<PresetCommandDataInfo> presetCommandDatas = jsonObject.getList("presetCommandDatas", PresetCommandDataInfo.class);
        Long terminalId = jsonObject.getLong("terminalId");
        TerminalsDb terminalsDb = terminalsDbService.selectTerminalsDbById(terminalId);
        List<PresetCommandDataInfo> result = null;
        try {
            result = terminalsDbCommandService.sendPresetReadCommand(terminalsDb, presetCommandDatas);
        } catch (Exception e) {
            logger.error("下发命令——多参数读取失败", e);
            return error("下发命令——多参数读取失败");
        }
        return success(result);
    }

    /**
     * 下发命令——多参数设置
     */
    @PostMapping("/sendPresetWriteCommand")
    @PreAuthorize("@ss.hasPermi('terminalsDbCommand:write')")
    public AjaxResult sendPresetWriteCommand(@RequestBody JSONObject jsonObject) {
        List<PresetCommandDataInfo> presetCommandDatas = jsonObject.getList("presetCommandDatas", PresetCommandDataInfo.class);
        Long terminalId = jsonObject.getLong("terminalId");
        // 命令类型（1：预置命令，2：实时命令）
        int commandType = jsonObject.getIntValue("commandType", 1);
        TerminalsDb terminalsDb = terminalsDbService.selectTerminalsDbById(terminalId);
        try {
            return toAjax(terminalsDbCommandService.sendPresetWriteCommand(terminalsDb, presetCommandDatas, commandType));
        } catch (Exception e) {
            logger.error("下发命令——多参数设置失败", e);
            return error("下发命令——多参数设置失败");
        }
    }
}
